layui.use(['laytpl', 'element'], function () {
	// 基础数据加载
	$(document).on('doc-user', function () {
		loadCache('/admin/api/user.json', function (res) {
			$('[data-doc-user="username"]').html(res.data.name);
			$('[data-doc-user="hotimage"]').removeClass('layui-hide');
			$('[data-doc-user="hotimage"]').attr('src', res.data.icon);
		});
	}).on('doc-menu', function () {
		var docMenuRoot = $('[lay-filter="docMenuRoot"]');
		var identity = docMenuRoot.data('identity');

		// 加载菜单
		loadCache('/admin/api/menu.json', function (res) {
			layui.laytpl( `{{# for(var i in d){ }}
					<li class="layui-nav-item">
					{{# if(d[i].children.length == 0){ }}
						<a href="{{d[i].linkurl}}" data-code="{{d[i].code}}" data-identity="{{d[i].identity}}">{{d[i].name}}</a>
					{{# } else { }}
						<a class="" href="javascript:;" data-code="{{d[i].code}}" data-identity="{{d[i].identity}}">{{d[i].name}}</a>
						<dl class="layui-nav-child">
							{{# for(var j in d[i].children){ }}
							{{# var children = d[i].children[j]; }}
							<dd><a href="{{children.linkurl}}" data-code="{{children.code}}" data-identity="{{children.identity}}">{{children.name}}</a></dd>
							{{# } }}
						</dl>
					{{# } }}
					</li>
				{{# } }}`).render(res.data, function (html) {
				docMenuRoot.html(html);

				// 添加选择的菜单样式
				var _this = docMenuRoot.find('[data-identity="' + identity + '"]');

				if (_this.length > 0) {
					_this.addClass('layui-this');
					_this.parents('.layui-nav-item').addClass('layui-nav-itemed');
				} else {
					_this = docMenuRoot.find('.layui-nav-item:eq(0)');

					if (_this.find('dd:eq(0)').length > 0) {
						_this.addClass('layui-nav-itemed');
						_this.find('dd:eq(0)').addClass('layui-this');
					} else {
						_this.addClass('layui-this');
					}
				}

				// 刷新菜单
				layui.element.render('nav', 'docMenuRoot');
			});
		});
	}).on('doc-load', function () {
		$(this).triggerHandler('doc-user');
		$(this).triggerHandler('doc-menu');
	}).on('doc-reload', function () {
		// 清理缓存
		removeCache('/admin/api/user.json');
		removeCache('/admin/api/menu.json');

		// 触发重新加载
		$(this).triggerHandler('doc-user');
		$(this).triggerHandler('doc-menu');
	}).triggerHandler('doc-load');

	// 加载缓存
	function loadCache(url, callback) {
		if (sessionStorage['cache-' + url]) {
			callback(JSON.parse(sessionStorage['cache-' + url]));
		} else {
			$.get(url, function (result) {
				if (result.success) {
					sessionStorage['cache-' + url] = JSON.stringify(result);

					callback(result);
				} else {
					console.error('加载数据失败：' + result.message);
				}
			});
		}
	}

	// 删除缓存
	function removeCache(url) {
		sessionStorage.removeItem('cache-' + url);
	}
});


